// cluster/cluster-start.js
const cluster = require('cluster');
const os = require('os');

function startCluster(startWorkerCallback) {
  const numCPUs = os.cpus().length;

  if (cluster.isPrimary) {
    console.log(`主进程 ${process.pid}，启动 ${numCPUs} 个子进程`);

    for (let i = 0; i < numCPUs; i++) {
      cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
      console.warn(`子进程 ${worker.process.pid} 退出，重启中...`);
      cluster.fork();
    });
  } else {
    startWorkerCallback(); // 启动子进程逻辑
  }
}

module.exports = startCluster;
